dojo.provide("medryx.widgets._TeamList.TeamListView");
dojo.require("medryx.AbstractBase")

dojo.declare("medryx.widgets._TeamList.TeamListView", medryx.AbstractBase, {
    //*** attributes
    //query the teams
    query:null,
    
    //sort the teams. this can be an array of sort objects (see AbstractDao.sort)
    //or can be a comma-seperated list of fields (simpler, but less flexible)
	
    sort:null,
    title:"Teams",
	footer:"",
	
    //*** internal
    templatePath: dojo.moduleUrl("medryx","widgets/_TeamList/TeamList.html"),
    teams:null,
    
	//abstract loadTeam(kwArguments) -- must return a list of teams to display
    $loadTeams:null,
    
    postCreate:function() {
        var actualSort = this.validateSort(this.sort);
        var actualQuery = this.validateQuery(this.query);
        this.load({
            query: actualQuery,
            sort: actualSort
        });
    },
    
    /**
     * currently just a stub
     * @param {Object} originalQuery
     */
    validateQuery:function(originalQuery) {
        return originalQuery;
    },
    
    /**
     * parse a sort string or array
     * guarantees returning an array 
     * of sort objects with their field
     * attribute set.
     * @param {Object} originalSort
     */
    _parseInSort:function(originalSort) {
        if (originalSort) {
            if (dojo.isString(originalSort)) {
                var fields = originalSort.split(/,\s*?/);
                originalSort = dojo.map(fields, function(field){
                    return {
                        attribute:dojo.trim(field)
                    };
                });
            }
            else 
                if (dojo.isArray(originalSort) && originalSort.length > 0) {
                    originalSort = dojo.map(originalSort, function(field){
                        if (field.attribute) {
                            return field;
                        }
                        else {
                            return {
                                attribute:dojo.trim(field)
                            };
                        }
                    });
                }
        } else {
            originalSort = [];
        }
        return originalSort;
    },
    
    /**
     * create the sort that will actually be used
     * when gathering the teams.
     * @param {Object} originalSort
     */
    validateSort:function(originalSort) {
        originalSort = this._parseInSort(originalSort);
        var actualSort = [{attribute:"categorySortIndex"}, {attribute:"category"}, {attribute:"name"}]; 
        
        if (originalSort.length > 0) {
            actualSort = actualSort.concat(originalSort);
        } 
		
        return actualSort;
    },

    /**
     * delegate to the controller.
     */
    load:function(args) {
        var deferred = this.loadTeams(args);
        deferred.addCallback(dojo.hitch(this, this.displayTeams, this.tableBody, this.headerCell, this.footerCell));
    },
    
    /**
     * hack to allow IE to handle "hover" behavior on row
     * @param {Object} e
     */
    onMouseOverRow:function(row, event) {
        dojo.addClass(row, "hover");
    },
    onMouseOutRow:function(row, event) {
        dojo.removeClass(row, "hover");
    },
    
    makeCategoryHeader:function(category) {
        var tr = dojo.doc.createElement("tr");
        var th = dojo.doc.createElement("th");
        tr.appendChild(th);
        th.colSpan = "2";
        th.innerHTML = category;
        dojo.addClass(tr, "teamListCategoryRow");
        return tr;
    },
    
    /**
     * creates a detail cell for the team
     * by displaying the pager numbers.
     * the detail cell is also given a class
     * of TeamListDetailCell
     * @param {Object} team
     */
    createTeamDetailsCell:function(team) {
        var td = dojo.doc.createElement("td");
        dojo.addClass(td, "teamListDetailCell");
        if (team.getPagers()) {
            if (team.getPagers().length == 1) {
                td.innerHTML = team.getPagers()[0].getPager().getPhoneNumber();
            
            } else if (team.getPagers().length > 1) {
                
                td.innerHTML = dojo.map(team.getPagers(), function(pager) {
                    return pager.getPager().getPhoneNumber() + " (" + pager.getType() + ")";
                }).join("<br>");
               
            }
        }
        return td;
    },
    
    /**
     * create a row for displaying a team
     * the first cell is the team name.
     * the second cell is passed to createTeamDetailsCell()
     * to create the "details"
     * 
     * also wires up each row, so that when it is clicked
     * it calles onTeamClicked(team, event);
     * @param {Object} team
     * @param {Object} count
     */
    makeTeamRow:function(team, count) {
        var tr = dojo.doc.createElement("tr");
        dojo.connect(tr, "onmouseover", dojo.hitch(this, "onMouseOverRow", tr));
        dojo.connect(tr, "onmouseout", dojo.hitch(this, "onMouseOutRow", tr));
        
        if (count % 2 == 0) {
            dojo.addClass(tr, "even");
        } else {
            dojo.addClass(tr, "odd");
        }
        
        var td = dojo.doc.createElement("td");
        tr.appendChild(td);
       
        var a = dojo.doc.createElement("a");
        td.appendChild(a);

        a.innerHTML = team.getName();
        a.href=team.getName();
		a.onclick = function(){
			return false;
		};

        dojo.connect(tr, "onclick", dojo.hitch(this, "onTeamClicked", team));
        
        var td = this.createTeamDetailsCell(team);
        tr.appendChild(td);
        
        
        return tr;
    },
    
    /**
     * event thrown when a team has been clicked
     * by the user
     * @param {Object} team
     * @param {Object} event
     */
    onTeamClicked:function(team, event) {
        
    },
    
	getHeaderContent:function() {
		return this.title;
	},
	
	getFooterContent:function() {
		return this.footer;
	},
	
    /**
     * display the teams on the widget. iterates through
     * each team and creates a row correponding to each.
     * Also creates a row corresponding to each 
     * "category", with the class "teamListCategoryRow"
     * 
     * @param {Object} items
     */
    displayTeams:function(tbody, headerCell, footerCell, teams) {
        var currentCategory = "";
        
		headerCell.innerHTML = this.getHeaderContent();
        footerCell.innerHTML = this.getFooterContent();
    
        dojo.forEach(teams, function(team, index) {
            if (currentCategory != team.getCategory()) {
                currentCategory = team.getCategory();
                tbody.appendChild(this.makeCategoryHeader(currentCategory));
            }
            
            tbody.appendChild(this.makeTeamRow(team, index));

        }, this);
		
    }
});
